import React, { useEffect, useState } from 'react';
import { Button, Card, Col, Form, Input, Modal, Pagination, Row, Select, Space, Upload, message, Empty } from 'antd';
import { PlusOutlined, UploadOutlined, SearchOutlined } from '@ant-design/icons';
import styles from './index.less';
import {addProtocolByJar, deleteProtocolById, protocolFileUpload} from "@/api/openapi/openapi";
import {queryOpenApiProtocolForPost} from "@/api/protocol/protocol";

// 文件类型定义
interface FileItem {
  id: string;
  name: string;
  location: string;
  description?: string;
}

// 文件卡片组件
const FileCard: React.FC<{ file: FileItem; onEdit: (file: FileItem) => void; onDelete?: (file: FileItem) => void }> = ({ file, onEdit, onDelete }) => {
  return (
    <Card
      hoverable
      className={styles.fileCard}
      actions={[
        <div className={styles.cardActions} key="actions">
          <Button type="link" key="edit" onClick={() => onEdit(file)} style={{ color: '#1890ff' }}>
            <span role="img" aria-label="编辑">✏️</span> 编辑
          </Button>
          <Button type="link" key="delete" danger onClick={() => onDelete && onDelete(file)}>
            <span role="img" aria-label="删除">🗑️</span> 删除
          </Button>
        </div>
      ]}
    >
      <div className={styles.fileIcon}>
        <img src="/openapi/file-icon.svg" alt="文件图标" />
      </div>
      <div className={styles.fileInfo}>
        <div className={styles.fileName}>{file.name}</div>
        <div className={styles.fileId}>{file.description}</div>
        {/*<div className={styles.fileType}>{file.type}</div>*/}
      </div>
    </Card>
  );
};

// 文件上传弹窗组件
const FileFormModal: React.FC<{
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  initialValues?: FileItem;
  title: string;
}> = ({ visible, onCancel, onSubmit, initialValues, title }) => {
  const [form] = Form.useForm();
  const [fileUrl, setFileUrl] = useState<string>('');

  useEffect(() => {
    if (!initialValues) {
      form.setFieldValue("name", "")
      return;
    }
    form.setFieldsValue({
      ...initialValues
    })
    setFileUrl(initialValues.location)
  }, [initialValues]);

  const handleUpload = async (file: any) => {
    try {
      const res = await protocolFileUpload(file);
      if (res?.status === 200) {
        setFileUrl(res?.result || '');
        form.setFieldsValue({ location: res.result });
        console.log('form',form.getFieldsValue())
        message.success('文件上传成功');
      }
    } catch (error) {
      message.error('文件上传失败');
    }
  };

  const handleSubmit = () => {
    form.validateFields().then(values => {
      console.log('values', values)
      onSubmit(values)
    }).catch(err => {
      console.error('表单验证失败:', err);
    });
  };

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
      >
        <Form.Item
          name="name"
          label="名称"
          rules={[{ required: true, message: '请输入文件名称' }]}
        >
          <Input placeholder="请输入文件名称" />
        </Form.Item>

        <Form.Item label="上传文件" name="location" rules={[{ required: true, message: '请上传文件' }]}>
          <div>
            <Upload
              customRequest={({ file }) => handleUpload(file)}
              showUploadList={true}
            >
              <Button icon={<UploadOutlined />} style={{ width: '100%', height: '40px', marginBottom: '8px' }}>
                {fileUrl ? '文件已上传，点击重新上传' : '点击上传文件'}
              </Button>
            </Upload>
            <Input
              value={fileUrl}
              placeholder="文件路径将在上传成功后显示"
              readOnly
              style={{ width: '100%' }}
            />
          </div>
        </Form.Item>

        <Form.Item
          name="description"
          label="说明"
        >
          <Input.TextArea placeholder="请输入说明" maxLength={200} showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
};

const ProtocolPage: React.FC = () => {
  const [fileList, setFileList] = useState<OpenApiProtocolEntity[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentFile, setCurrentFile] = useState<FileItem | undefined>(undefined);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchText, setSearchText] = useState<string>('');
  const pageSize = 12;

  const fetchApiProtocolList = (queryParam: QueryParamEntity)=>{
    queryOpenApiProtocolForPost(queryParam).then(res => {
      setFileList(res?.result?.data || [])
      setTotal(res?.result?.data?.length || 0);
    })
  }

  // 模拟获取文件列表数据
  useEffect(() => {
    // 这里应该是从API获取数据
    // 模拟数据
    fetchApiProtocolList({})
  }, []);

  const handleAdd = () => {
    setCurrentFile(undefined);
    setModalVisible(true);
  };

  const handleEdit = (file: FileItem) => {
    setCurrentFile(file);
    setModalVisible(true);
  };

  const handleDelete = (file: FileItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除「${file.name}」吗？`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteProtocolById(file.id).then(res => {
          fetchApiProtocolList({})
          message.success('文件删除成功');
        })
      }
    });
  }

  const handleSubmit = (values: any) => {
    if (currentFile) {
      // 更新文件
      const updatedList = fileList.map(item =>
        item.id === currentFile.id ? { ...item, ...values } : item
      );
      setFileList(updatedList);
      message.success('文件更新成功');
    } else {
      // 设置默认类型，确保后端接口兼容性
      addProtocolByJar(values).then(res => {
        fetchApiProtocolList({})
        setModalVisible(false)
      })
      message.success('文件添加成功');
    }
    setModalVisible(false);
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    // 这里应该调用API获取对应页的数据
  };

  // 根据搜索文本过滤文件列表
  const filteredFileList = React.useMemo(() => {
    if (!searchText) return fileList;
    return fileList.filter(
      (file) =>
        file.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (file.description?.toLowerCase().includes(searchText.toLowerCase()) ?? false)
    );
  }, [fileList, searchText]);

  // 计算当前页显示的文件
  const currentFiles = filteredFileList.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Space size="large" style={{ width: '100%', justifyContent: 'space-between' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </Button>
          <div style={{ position: 'relative', width: '300px' }}>
            <Input
              placeholder="✨ 搜索文件 ✨"
              prefix={<SearchOutlined style={{ fontSize: '16px', color: '#1890ff' }} />}
              value={searchText}
              onChange={(e) => {
                setSearchText(e.target.value)
                setCurrentPage(1); // 搜索时重置为第一页
                fetchApiProtocolList({
                  terms:[
                    {
                      column: 'name',
                      termType: 'like',
                      value: `%${e.target.value}%`
                    }
                  ]
                })
              }}
              style={{
                width: '100%',
                height: '40px',
                padding: '8px 16px',
                fontSize: '14px',
                borderRadius: '20px',
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
                border: '2px solid transparent',
                background: 'linear-gradient(white, white) padding-box, linear-gradient(45deg, #1890ff, #69c0ff) border-box',
                transition: 'all 0.3s ease',
              }}
              allowClear
            />
          </div>
        </Space>
      </div>

      {fileList.length > 0 ? (
        <Row gutter={[16, 16]} className={styles.fileList}>
          {currentFiles.map(file => (
            <Col xs={24} sm={12} md={8} lg={6} key={file.id}>
              <FileCard file={file} onEdit={handleEdit} onDelete={handleDelete} />
            </Col>
          ))}
        </Row>
      ) : (
        <Empty description={searchText ? "没有找到匹配的文件" : "暂无文件"} style={{ marginTop: 48 }} />
      )}

      <div className={styles.pagination}>
        <Pagination
          current={currentPage}
          total={filteredFileList.length}
          pageSize={pageSize}
          onChange={handlePageChange}
          showTotal={(total) => `第 ${currentPage} 页/共 ${Math.ceil(total / pageSize)} 页`}
        />
      </div>

      <FileFormModal
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onSubmit={handleSubmit}
        initialValues={currentFile}
        title={currentFile ? '修改' : '新增'}
      />
    </div>
  );
};

export default ProtocolPage;
